<template>
	<div class="list-table">
		<el-table
		v-loading="loading"
		element-loading-text="拼命加载中"
		element-loading-spinner="el-icon-loading"
		element-loading-background="rgba(255, 255, 255, 0.92)"
		ref="multipleTable"
		:data="list"
		row-key="id"
		tooltip-effect="dark"
		style="width: 100%"
		:height="height"
		@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" v-if="batch && batch.length>0"></el-table-column>
			<slot name="data"></slot>
		</el-table>
		<div class="footer" v-if="footer">
			<div class="l">
				<div v-if="batch && batch.length>0">
					<el-button @click="toggleSelection()">取消选择</el-button>
					<el-button v-if="batch.length<=3" v-for="(item, index) in batch" :key="index" @click="batchChange(item)">{{ item.label }}</el-button>
					<el-select v-model="flag" placeholder="批量操作" @change="batchChange" v-if="batch.length>3">
						<el-option
							v-for="item in batch"
							:key="item.id"
							:label="item.label"
							:value="item.id">
						</el-option>
					</el-select>
				</div>
			</div>
			<el-pagination
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange"
			:background="true"
			:current-page="pagination.currPage"
			:page-sizes="[10, 20, 50, 100]"
			:page-size="pagination.pageSize"
			layout="total, sizes, prev, pager, next, jumper"
			:total="pagination.count">
			</el-pagination>
		</div>
	</div>
</template>

<script>
import Sortable from 'sortablejs'//拖动排序，参考地址https://www.cnblogs.com/jin-zhe/p/10181852.html
export default {
	inject: ['reload'],
	props: ['list', 'tableLoading', 'footer', 'pagination', 'sort', 'batch', 'height', 'appid'],
	data() {
		return {
			multipleSelection: [],
			loading: true,
			flag: ''//选择的批量操作值
		};
	},
	mounted() {
		this.rowDrop()
		/*没有传tableLoading的话，不要显示加载*/
		if(this.tableLoading == undefined){
			this.loading = false
		}
	},
	methods: {
		toggleSelection(rows) {
			if (rows) {
				rows.forEach(row => {
					this.$refs.multipleTable.toggleRowSelection(row);
				});
			} else {
				this.$refs.multipleTable.clearSelection();
			}
		},
		handleSelectionChange(val) {
			this.multipleSelection = val;
		},
		/*选择每页显示多少条信息*/
		handleSizeChange(val) {
			// console.log(`每页 ${val} 条`);
			this.$get(this.$api.setPageSize, {
				appid: (this.appid != '')?this.appid:'',
				'pageSize': val
			}).then(res => {
				// console.log(res);
				if(res.data.code == 10007){//后台提示需要登录
					this.$cookie.remove('isLogin');//刪除cookie登录信息
					this.reload();
				}
				if(res.data.code === 0){
					this.reload();
				}
			})
			.catch(err => {})
			.finally(() => {})
		},
		/*点击页码、上页、下页、页面跳转*/
		handleCurrentChange(val) {
			// console.log(`当前页: ${val}`);
			let query
			if(this.$route.fullPath.indexOf('page=') == -1){
				query = Object.assign({page: val}, this.$route.query)
			}else{
				query = JSON.parse(JSON.stringify(this.$route.query))
				query.page = val
			}
			this.$router.push({query})
		},
		//拖拽一行
		rowDrop() {
			const tbody = document.querySelector('.el-table__body-wrapper tbody')
			const _this = this
			if(this.sort){
				Sortable.create(tbody, {
					onEnd({ newIndex, oldIndex }) {
						_this.$emit('setSort', newIndex, oldIndex)
					}
				})
				// this.sortable = Sortable.create(tbody, {
				// 	animation: 180,
				// 	delay: 0,
				// 	onEnd: evt => {
				// 		// console.log(this.list, 111)
				// 		// console.log(evt.item)
				// 	}
				// })
			}
		},
		/*批量操作，下拉菜单值改变*/
		batchChange(val) {
			// console.log(val)
			if(typeof(val) == 'object'){//说明是单个按钮点击的
				var flag = val.id
				var message = val.label
			}else{//说明是下拉菜单选择的
				// console.log(val, 11)
				var flag = this.flag
				var message = this.__getMenuBySelect(flag)
			}
			// console.log(this.__setBatchData(), 1)
			// this.__setBatchData();
			let data = this.__setBatchData()//需要操作的数据
			if(data.length){
				this.$confirm('此操作将 <' + message + '> 选中数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$emit('batchChange', flag, data)
					// this.$message({
					// 	type: 'success',
					// 	message: '删除成功!'
					// });
				}).catch(() => {
					// this.$message({
					// 	type: 'info',
					// 	message: '已取消删除'
					// });
					this.flag = ''
				});
			}else{
				this.$message({
					showClose: true,
					message: '至少选择一项！',
					type: 'warning'
				});
				this.flag = ''
			}
		},
		/*把选中的所有项，抽出ID,一般是第一个, 以为有的id名称不一样，所以取第一个，如果传过来的数据，第一个不是主键值，将会报错*/
		__setBatchData() {
			let res = []//返回值
			this.$refs.multipleTable.selection.forEach((item, index) => {
				let idKey = Object.keys(item)[0]//id键名
				res.push(item[idKey])
			})
			return res
		},
		/*根据选中的下拉值，返回对应的菜单*/
		__getMenuBySelect(val){
			let res = '';
			this.batch.forEach((item, index) => {
				if(item.id == parseInt(val)){
					res = item.label
				}
			})
			return res;
		}

	},
	watch: {
		tableLoading(val) {
			if(!val){
				this.loading = false
			}else{
				this.loading = true
			}
		}
	},
	computed: {

	}
};
</script>

<style lang="stylus" scoped>
.list-table
	margin-top: 10px
	border: 1px solid #e9ecf4
	/deep/ .has-gutter
		background-color: #f4f5f9 !important
	.footer
		margin: 10px
		display: flex
		.l
			flex: 1
// /deep/ .el-table__body
// 	width: 300px !important
// /deep/ .el-table__header
// 	width: 300px !important
// /deep/ .el-table__empty-block
// 	width: 300px !important
</style>